﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DGSFramework;
using System.Web.Security;
using System.Xml.Linq;
using System.Text.RegularExpressions;

namespace Framework.WebmasterTool
{
    public partial class RewriteURL : System.Web.UI.Page
    {
        DGSFrameworkEntities entity = new DGSFrameworkEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                CheckPermission();
                LoadRewriteURL();
            }
        }

        public void CheckPermission()
        {
            MembershipUser someUser = Membership.GetUser();
            if (someUser == null)
            {
                Response.Redirect(Globals.ApplicationPath + "LoginAdmin/Default.aspx");
            }
            bool flag = false;
            var user = entity.aspnet_Users.Where(us => us.UserName == someUser.UserName).FirstOrDefault();
            user.aspnet_Roles.Load();
            var rolesForUser = user.aspnet_Roles.ToList();
            foreach (var item in rolesForUser)
            {
                var permission = entity.udv_Permissions.Where(ps => ps.RoleId == item.RoleId).FirstOrDefault();
                if (permission.RewriteURL.Value == true)
                {
                    flag = true;
                }
            }
            if (flag == false)
            {
                lblPermissionMessage.Visible = true;
                Panel1.Visible = false;
            }
        }

        public void LoadRewriteURL()
        {
            XDocument xDocRewrite = XDocument.Load(HttpContext.Current.Server.MapPath(ConfigPaths.Path_Rewrite_Xml));
            XElement XEEnable = xDocRewrite.Descendants("Enable").FirstOrDefault();
            ddlRewriteMode.SelectedValue = XEEnable.Value.Trim();
            txtRewriteExtension.Text = Globals.GetUrlRewriteExtension();
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            string urlExtensionOld = Globals.GetUrlRewriteExtension();
            XDocument xDocRewrite = XDocument.Load(Server.MapPath(ConfigPaths.Path_Rewrite_Xml));
            XElement XEEnable = xDocRewrite.Descendants("Enable").FirstOrDefault();
            XEEnable.Value = ddlRewriteMode.SelectedValue.Trim();
            XElement XEUrlExtension = xDocRewrite.Descendants("UrlExtension").FirstOrDefault();
            XEUrlExtension.Value = txtRewriteExtension.Text.Trim();
            xDocRewrite.Save(Server.MapPath(ConfigPaths.Path_Rewrite_Xml));
            if (txtRewriteExtension.Text.Trim() != urlExtensionOld)
            {
                UpdateINI_UrlList_ROR_Sitemap("\\urlRules.config", string.IsNullOrEmpty(urlExtensionOld) ? ".html" : urlExtensionOld, string.IsNullOrEmpty(txtRewriteExtension.Text.Trim().ToLower()) ? ".html" : txtRewriteExtension.Text.Trim().ToLower());
                UpdateINI_UrlList_ROR_Sitemap("\\IIRF.INI", string.IsNullOrEmpty(urlExtensionOld) ? ".html" : urlExtensionOld, string.IsNullOrEmpty(txtRewriteExtension.Text.Trim().ToLower()) ? ".html" : txtRewriteExtension.Text.Trim().ToLower());
                UpdateINI_UrlList_ROR_Sitemap("\\urllist.txt", string.IsNullOrEmpty(urlExtensionOld) ? ".html" : urlExtensionOld, string.IsNullOrEmpty(txtRewriteExtension.Text.Trim().ToLower()) ? ".html" : txtRewriteExtension.Text.Trim().ToLower());
                UpdateINI_UrlList_ROR_Sitemap("\\ror.xml", string.IsNullOrEmpty(urlExtensionOld) ? ".html" : urlExtensionOld, string.IsNullOrEmpty(txtRewriteExtension.Text.Trim().ToLower()) ? ".html" : txtRewriteExtension.Text.Trim().ToLower());
                UpdateINI_UrlList_ROR_Sitemap("\\sitemap.xml", string.IsNullOrEmpty(urlExtensionOld) ? ".html" : urlExtensionOld, string.IsNullOrEmpty(txtRewriteExtension.Text.Trim().ToLower()) ? ".html" : txtRewriteExtension.Text.Trim().ToLower());
            }
            lblMessage.Text = "Cập nhật thành công";
            //create db log
            CreateDBLog(null, null, TypeAction.Update, "Cập nhật cấu hình đường dẫn thân thiện", "", "", "", "", "", "", "", "");
        }

        public void UpdateINI_UrlList_ROR_Sitemap(string saveMapPath_INI_UrlList_ROR_Sitemap, string urlExtensionOld, string urlExtensionNew)
        {
            string content = "";
            System.IO.StreamReader StreamReader1 = new System.IO.StreamReader(HttpContext.Current.Server.MapPath(saveMapPath_INI_UrlList_ROR_Sitemap));
            content = StreamReader1.ReadToEnd();
            StreamReader1.Close();
            content = Regex.Replace(content, urlExtensionOld, urlExtensionNew);

            System.IO.StreamWriter StreamWriter1 = new System.IO.StreamWriter(HttpContext.Current.Server.MapPath(saveMapPath_INI_UrlList_ROR_Sitemap));
            StreamWriter1.Write(content);
            StreamWriter1.Close();
        }

        public void CreateDBLog(int? postID, int? postCateID, TypeAction typeAction, string title, string _abstract, string description,
        string releaseDate, string expireDate, string isApproved, string statusID, string metaDescription, string metaKeywords)
        {
            udv_Log log = new udv_Log();
            log.PostID = postID;
            log.PostCateID = postCateID;
            log.TypeAction = (int)typeAction;
            log.Title = title;
            log.Abstract = _abstract;
            log.Description = description;
            log.ReleaseDate = releaseDate;
            log.ExpireDate = expireDate;
            log.IsApproved = isApproved;
            log.StatusID = statusID;
            log.MetaDescription = metaDescription;
            log.MetaKeywords = metaKeywords;
            log.ActionedDate = DateTime.Now;
            log.ActionBy = Membership.GetUser().UserName;
            log.IpAdress = Globals.GetClientIPAddress();

            entity.AddToudv_Log(log);
            entity.SaveChanges();
        }
    }
}